package com.hundsun.yr.universal.p2p.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.base.BaseWebActivity.LoadType;
import com.hundsun.yr.universal.library.common.KeyBoardUtils;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.HSJSONTools;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog.HSDialogOnItemClickListener;
import com.hundsun.yr.universal.library.view.itemview.BasicItemViewH;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSEditText;
import com.hundsun.yr.universal.p2p.bean.BeforeInvestBean;
import com.hundsun.yr.universal.p2p.bean.DiscountBeen;
import com.hundsun.yr.universal.p2p.bean.DiscountInfoBean;
import com.hundsun.yr.universal.p2p.bean.InvestBean;
import com.hundsun.yr.universal.p2p.bean.InvestProtocolBean;
import com.hundsun.yr.universal.p2p.bean.UpdatePayPwdBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.bean.enums.EnumProtocol;
import com.hundsun.yr.universal.p2p.bean.enums.OssidEnum;
import com.hundsun.yr.universal.p2p.config.ApiConstants2;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializeTargetPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @version V1.0
 * @Title: InvestmentActivity.java
 * @Description: 投资页面
 * @date 2015-12-4 下午2:17:04
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class InvestActivity extends BaseActivity implements OnClickListener,
        InitializeView, HSDialogOnItemClickListener {
    /**
     * 优惠抵扣
     **/
    private BasicItemViewH bv_preferential = null;
    /**
     * 应付金额
     **/
    private BasicItemViewH bv_payable = null;
    /**
     * 立即投资购买按钮
     **/
    private HSButton btn_buy = null;
    /**
     * 全额按钮
     **/
    private HSButton btn_all = null;
    /**
     * 投资金额
     **/
    private HSEditText et_investmoney = null;
    /**
     * 充值弹窗
     **/
    private HSDialog dialog_rechange = null;
    /**
     * 购买弹窗
     **/
    private HSDialog dialog_buy = null;
    /**
     * 错误文本
     **/
    private TextView tv_error = null;
    /**
     * 预期收益
     **/
    private TextView tv_incomesum = null;
    /**
     * 商品ID
     **/
    private String goodsId = "";
    /**
     * 营销商品ID
     **/
    private String mktGoodsId = "";
    /**
     * 所有数据
     **/
    private String returnObj = "";
    /**
     * 最小递增金额
     **/
    private String addMoney;
    /**
     * 起投金额
     **/
    private String startMoney;
    /**
     * 剩余金额
     **/
    private String surplus;
    /**
     * 单笔购买最大金额
     **/
    private String maxSingleMny;
    /**
     * 利率
     **/
    private String rate;
    /**
     * 投资期限类型
     **/
    private String ivsmTmLmtType;
    /**
     * 投资期限
     **/
    private String ivsmTmLmt;
    /**
     * 投资时间
     **/
    private String ivstime;
    /**
     * 投资金额
     **/
    private String investAmnt;
    /**
     * 请求接口
     **/
    private RequestPresenter mPresenter = null;
    /**
     * 优惠ID
     **/
    private String discountId = "";
    /**
     * 订单编号
     **/
    private String orderNo;
    /**
     * 借款协议
     **/
    private TextView tv_protocol = null;

    /**
     * 风险评估揭示书
     */
    private TextView tv_protocol_1 = null;
    /**
     * 协议选择
     **/
    private CheckBox ck_agree = null;
    /**
     * 协议链接
     **/
    private String mUrl;
    /**
     * 协议字符串
     **/
    private String protocol = "";
    /**商品对象**/
//    private HashMap<String, String> map;
    /**
     * 商品对象
     **/
    private InvestBean invest = null;
    /**
     * 选中优惠对象
     **/
    private DiscountInfoBean discount = null;
//	private String discount;//优惠卷id或者价格
    /**
     * 商品名称
     **/
    private String mktGdsName;
    /**新的商品对象**/
//	private ProductBeen mProductBeen = null;
    /**
     * 投资期数
     **/
    private String term = "0";
    /**
     * 还款方式，默认等额本息
     **/
    private String pay_method = "1";
    /**
     * 最小起投金额
     **/
    private String invest_min = "";
    /**
     * 最大投资金额
     **/
    private String invest_max = "";
    /**
     * 全额
     **/
    private String all_money = "";
    /**
     * 由哪个页面点进来
     **/
    private String flag = "TOUZI";
    private String surplusAmount;
    private HSDialog riskDialog;
    private HSDialog riskSureDialog;
    private HSDialog authDialog;
    private String zwgt_data;
    private String uuid = "";
    private String investstep = "1000";
    //总金额
    private String debt;
    //已借金额
    private String raise_amount;
    /**
     * 新手标
     */
    private String recruit_flag;

    private TextView surplus_amount_and_user_amount;
    private String subtract;
    private int PREFERENTIAL = 1;
    private HSDialog paypwdDialog;

    /**
     * 现金列表
     **/
    private List<DiscountBeen.DiscountBean> data_cash = new ArrayList<DiscountBeen.DiscountBean>();

    private List<DiscountBeen.DiscountBean> can_use_data_cash = new ArrayList<>();
    private String redEnvelop;
    private String discount_money = "";

    //能用的最小的钱
    private String discount_can_user_min_money;
    private String use_discount_flag;


    @Override
    protected boolean isApplyKitKatTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        goodsId = extras.getString(Extras.GDSID);//获得商品编号
        mktGdsName = extras.getString(Extras.MKTGDSNAME);//获得商品编号
        rate = extras.getString(Extras.RATE);
        term = extras.getString(Extras.TERM);
        pay_method = extras.getString(Extras.PAYMETHOD);
        invest_min = extras.getString(Extras.INVESTMIN);
        invest_max = extras.getString(Extras.INVESTMAX);
        all_money = extras.getString(Extras.ALLMONEY);
        flag = extras.getString(Extras.FLAG);
        investAmnt = extras.getString(Extras.INVEST_MONEY);
        uuid = extras.getString(Extras.UUID);
        investstep = extras.getString(Extras.INVESTSTEP);
        debt = extras.getString(Extras.DEBT);
        raise_amount = extras.getString(Extras.RAISE_AMOUNT);
        recruit_flag = extras.getString(Extras.RECRUIT_FLAG);
        use_discount_flag = extras.getString(Extras.USE_DISCOUNT_FLAG);
    }

    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.act_invest;
    }

    /**
     * 接受eventBus返回的数据
     *
     * @param eventCenter
     */
    @SuppressWarnings("deprecation")
    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub
        switch (eventCenter.getEventCode()) {
            case Extras.ORDER_SUCCESS:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        LinearLayout linear_root = findView(R.id.linear_root);
        return linear_root;
    }

    @Override
    protected void initViewsAndEvents() {
        setToolbarTitle(mktGdsName);
        // TODO Auto-generated method stub
        tv_error = findView(R.id.tv_error);

        /**长条布局**/
        bv_preferential = findView(R.id.bv_preferential);
        bv_preferential.setOnClickListener(this);

        /**长条布局**/
        bv_payable = findView(R.id.bv_payable);

        /**预期收益的值**/
        tv_incomesum = findView(R.id.tv_incomesum);

        /**立即购买**/
        btn_buy = findView(R.id.btn_buy);
        btn_buy.setOnClickListener(this);

        btn_all = findView(R.id.btn_all);
        btn_all.setOnClickListener(this);

        surplus_amount_and_user_amount = findView(R.id.tv_surplus_amount_and_user_amount);

        /**EditText投资金额**/
        et_investmoney = findView(R.id.et_investmoney);
        et_investmoney.setText(investAmnt);
        et_investmoney.setHint(invest_min);
        et_investmoney.addTextChangedListener(textWatcher);
        income(investAmnt);

        if (use_discount_flag != null && !use_discount_flag.equals("1")) {
            bv_preferential.getmSubTitle().setText(getString(R.string.can_not_user_discount));
        }

        if (TextUtils.equals("WaitPayFragment", flag)) {
            btn_all.setVisibility(View.INVISIBLE);
            btn_all.setEnabled(false);
            et_investmoney.setRightIconVisible(false);
            et_investmoney.setEnabled(false);
            et_investmoney.setFocusable(false);
        }


        /**同意借款协议按钮**/
        ck_agree = findView(R.id.ck_agree);

        /**《借款协议》**/
        tv_protocol = findView(R.id.tv_protocol);
        /**从协议枚举类型中拿出一个借款协议**/
        tv_protocol.setText(getString(R.string._protocol, OssidEnum.INVESTMENT_PROTOCOL.getOssLabel()));
        tv_protocol.setOnClickListener(this);


        /**《风险评估揭示书》**/
        tv_protocol_1 = findView(R.id.tv_protocol_1);
        /**从协议枚举类型中拿出一个借款协议**/
        tv_protocol_1.setText(getString(R.string._protocol, OssidEnum.RISK_DISCLOSURE.getOssLabel()));
        tv_protocol_1.setOnClickListener(this);

        mPresenter = new InitializeTargetPresenterImpl(this, this);

        /**
         * 获取用户可用金额
         */
        surplusAmount = sharedPreferences.getShareProf(UserInfo.CAN_USE_MONEY) == null ? "0" : sharedPreferences.getShareProf(UserInfo.CAN_USE_MONEY);
        try {
            String subtract = MathUtils.subtract(debt, raise_amount);
            if (MathUtils.compare(subtract, invest_min) <= 0) {
                et_investmoney.setText(subtract);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        surplus_amount_and_user_amount.setText(getString(R.string.surplus_amount_and_user_amount, MathUtils.subtract(debt, raise_amount), CommTool.keep2Digits(surplusAmount)));

        loadingData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sharedPreferences.getShareProf(UserInfo.CAN_USE_MONEY) != null) {
            surplus_amount_and_user_amount.setText(getString(R.string.surplus_amount_and_user_amount, MathUtils.subtract(debt, raise_amount), CommTool.keep2Digits(sharedPreferences.getShareProf(UserInfo.CAN_USE_MONEY))));
        }
    }

    /**
     * 请求红包
     */
    /**
     * 加载数据
     */
    private void loadingData() {
        mPresenter = new InitializeTargetPresenterImpl(mContext, this);
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.TASK_DISCOUNT, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.
                TASK_DISCOUNT + "?goodsid=" + goodsId, Constants.EVENT_REFRESH_DATA, ApiConstants2.discount(goodsId), BaseRequestTool2.getHearder(mContext,
                TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.TASK_DISCOUNT + "?goodsid=" + goodsId, sharedPreferences.
                        getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }


    @Override
    protected void onNetworkConnected(NetType type) {
        // TODO Auto-generated method stub
    }

    @Override
    protected void onNetworkDisConnected() {
        // TODO Auto-generated method stub
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 各种点击事件，
     *
     * @param v
     */
    @SuppressWarnings("deprecation")
    @Override
    public void onClick(View v) {
        if (!NetUtils.isNetworkConnected(mContext)) {
            showProgressToDismiss();
            return;
        }

        if (isFastDoubleClick()) {
            return;
        }

        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.bv_preferential://传递map，符合条件的跳入优惠券页面
                discounts();
                break;
            case R.id.tv_protocol://借款协议
                protocol = "INVESTMENT_PROTOCOL";

                zwgt_data = BaseRequestTool2.getFormatedDateString();
                JSONObject map = new JSONObject();
                try {
                    map.put("uuid", uuid);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
                mPresenter.loadingData(TaskConstants.TASK_PROTOCOL, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_trade_test)
                        + TaskConstants.TASK_PROTOCOL, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_trade_test)
                        + TaskConstants.TASK_PROTOCOL, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
                break;

            case R.id.tv_protocol_1://风险揭示书
                protocol = "RISK_DISCLOSURE";

                zwgt_data = BaseRequestTool2.getFormatedDateString();
                JSONObject map2 = new JSONObject();
                try {
                    map2.put("uuid", uuid);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                JSONObject jsonParams2 = CommTool.getJSONParams(map2, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
                mPresenter.loadingData(TaskConstants.TASK_PROTOCOL, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_trade_test)
                        + TaskConstants.TASK_PROTOCOL, Constants.EVENT_DATA, jsonParams2, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_trade_test)
                        + TaskConstants.TASK_PROTOCOL, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
                break;
            case R.id.btn_buy://点击立即投资
                //余额充足购买
                investAmnt = et_investmoney.getText().toString();
                //投资金额部分
                if (TextUtils.isEmpty(investAmnt)) {
                    showToast(R.string.input_invest_money);
                    return;
                }

                if (discount_can_user_min_money != null && investAmnt != null && !discount_can_user_min_money.isEmpty() && !investAmnt.isEmpty()) {
                    if (MathUtils.compare(discount_can_user_min_money, investAmnt) > 0) {
                        showToast(getString(R.string.can_user_discount, CommTool.keep2Digits(discount_can_user_min_money)));
                        return;
                    }
                }

                //投资金额为递增金额的整数倍，如果是全部金额又可以投递
                subtract = MathUtils.subtract(debt, raise_amount);
                if (!subtract.isEmpty() && !MathUtils.equals(investAmnt, subtract)) {
                    //投资金额不等于剩余金额，如果投资金额等于剩余金额的时候不需要判断递增金额和判断最小金额
                    if (!MathUtils.equals(investAmnt, invest_min)) {
                        if (new Double(investAmnt) % new Double(investstep) != 0) {
                            showToast(getString(R.string._hint_invtest, invest_min, investstep));
                            return;
                        }
                    }

                    //判断最小
                    if (MathUtils.compare(investAmnt, invest_min) < 0) {
                        showToast(getString(R.string.input_invest_min, invest_min));
                        return;
                    }
                } else {
                    if (MathUtils.compare(subtract, invest_min) > 0) {
                        //投资金额不等于剩余金额，如果投资金额等于剩余金额的时候不需要判断递增金额和判断最小金额
                        if (new Double(investAmnt) % new Double(investstep) != 0) {
                            showToast(getString(R.string._hint_invtest, invest_min, investstep));
                            return;
                        }
                    }
                }


                if (invest_max != null && !invest_max.isEmpty() && MathUtils.compare(investAmnt, invest_max) > 0) {
                    showToast(getString(R.string.input_invest_max_, invest_max));
                    return;
                }

                if (MathUtils.compare(investAmnt, subtract) > 0) {
                    showToast(getString(R.string.input_invest_max));
                    return;
                }

                if (ck_agree.isChecked() == false) {//判断协议是否勾选
                    showToast(getString(R.string.tips_agree_protocol, OssidEnum.LOAN_SERVICE_PROTOCOL.getOssLabel()));
                    return;
                }

                if (!sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {//判断是否登陆
                    showToast(R.string.login_ever);
                    readyGo(LoginActivity.class);
                    return;
                }

                //投资金额必须大于抵扣金额
                if (discount != null && discount.money != null) {
                    if (MathUtils.compare(investAmnt, discount.money) <= 0) {
                        showToast(R.string.tips_amount_discount);
                        return;
                    }
                }

                KeyBoardUtils.getInstance(this).hide();//隐藏软键盘

                // TODO: 2017/6/16 点击立即投资的时候看看是不是要进行
                if (sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT) != null && TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT), "YES")) {

                    if (!TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_PAYPWD), "YES")) {//交易密码
                        paypwdDialog = new HSDialog(getString(R.string.tips), getString(R.string.tips_nopaypwd),
                                getString(R.string.cancel), getString(R.string.tips_go_set), mContext, this).setCancelable(false);
                        paypwdDialog.show();
                        return;
                    }

                    if (!bv_payable.getmSubTitle().getText().toString().isEmpty()) {
                        if (MathUtils.compare(bv_payable.getmSubTitle().getText().toString().substring(1), sharedPreferences.getShareProf(UserInfo.CAN_USE_MONEY)) > 0) {
                            readyGo(RechangeNewActivity.class);
                            return;
                        }
                    }

//                    if (sharedPreferences.getShareProf(UserInfo.OLD) != null){
//                        if (sharedPreferences.getShareProf(UserInfo.OLD).isEmpty() || MathUtils.compare(sharedPreferences.getShareProf(UserInfo.OLD),"18") < 0 || MathUtils.compare(sharedPreferences.getShareProf(UserInfo.OLD),"68") >= 0){
//                            showToast(getString(R.string.age_not_risk));
//                            return;
//                        }
//                    }

                    zwgt_data = BaseRequestTool2.getFormatedDateString();
                    JSONObject map1 = new JSONObject();

                    try {
                        map1.put("uuid", uuid);
                        map1.put("amount", investAmnt);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    JSONObject jsonParams1 = CommTool.getJSONParams(map1, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
                    mPresenter.loadingData(TaskConstants.TASK_BEFOREINVEST, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_trade_test) + TaskConstants.TASK_BEFOREINVEST, Constants.EVENT_DATA,
                            jsonParams1, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_trade_test) + TaskConstants.TASK_BEFOREINVEST, sharedPreferences
                                    .getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
                } else {
                    showToast(getString(R.string.open_account));
                    readyGo(OpenAccountBankActivity.class);
                }
                break;
            case R.id.btn_all:
                //全额
                if (TextUtils.equals(recruit_flag, "1")) {
                    et_investmoney.setText(invest_min);
                    return;
                }

                if (all_money != null && surplusAmount != null && !all_money.isEmpty() && !surplusAmount.isEmpty()) {
                    subtract = MathUtils.subtract(debt, raise_amount);
                    try {
                        if (MathUtils.compare(surplusAmount, invest_min) <= 0) {
                            if (MathUtils.compare(surplusAmount, subtract) < 0) {
                                showToast(R.string.balance_insufficient);
                            }

                            if (MathUtils.compare(subtract, invest_min) < 0) {
                                et_investmoney.setText(subtract);
                            } else {
                                et_investmoney.setText(invest_min);
                            }
                            return;
                        } else {
                            int v1 = (int) (new Double(surplusAmount) / new Double(invest_min));
                            String multiply = MathUtils.multiply(v1 + "", invest_min);

                            //                            showToast(R.string.balance_insufficient);
                            if (MathUtils.compare(surplusAmount, subtract) <= 0) {
                                //surplus小
                                if (MathUtils.compare(surplusAmount, invest_max) <= 0) {
                                    et_investmoney.setText(multiply);
                                } else {
                                    et_investmoney.setText(invest_max);
                                }
                            } else {
                                //subtract小
                                if (MathUtils.compare(subtract, invest_max) <= 0) {
                                    et_investmoney.setText(subtract);
                                } else {
                                    et_investmoney.setText(invest_max);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        et_investmoney.setText("");
                        return;
                    }
                } else {
                    et_investmoney.setText("");
                }


                investAmnt = et_investmoney.getText().toString();
                break;
            default:
                break;
        }
    }

    /**
     * 选择优惠校验，并且跳转优惠卷界面
     */
    private void discounts() {
        investAmnt = et_investmoney.getText().toString();

        if (use_discount_flag != null && !use_discount_flag.equals("1")) {
            return;
        }

        if (TextUtils.isEmpty(investAmnt)) {
            showToast(R.string.input_invest_money);
            return;
        }

        KeyBoardUtils.getInstance(this).hide();
        Bundle bundle = new Bundle();
        bundle.putString("GOODSNO", goodsId);

        readyGoForResult(PreferentialActivity.class, PREFERENTIAL, bundle);
    }


    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            income(s.toString());
            discountChoice(s.toString());
        }
    };

    /**
     * 对优惠券进行默认选取
     */
    private void discountChoice(String money) {
        //1、先挑选该条件下可以用的优惠券
        //2、再挑选出钱最大的那张
        //3、进行显示
        if (use_discount_flag != null && !use_discount_flag.equals("1")) {
            if (money != null || !money.isEmpty()) {
                bv_payable.getmSubTitle().setText(getString(R.string._rmb, money));
            }

            return;
        }

        can_use_data_cash.clear();
        if (money == null || money.isEmpty() || money.equals("0") || TextUtils.isEmpty(rate)) {
            bv_payable.getmSubTitle().setText(getString(R.string._rmb, 0));
            tv_incomesum.setText("0");
            bv_preferential.getmSubTitle().setText(R.string.no_choose);
            return;
        }

        if (data_cash.size() != 0) {
            for (int i = 0; i < data_cash.size(); i++) {
                if (MathUtils.compare(money, data_cash.get(i).min_money) >= 0) {
                    //符合条件将优惠券挑选出来
                    can_use_data_cash.add(data_cash.get(i));
                }
            }
        }

        String maxDiscount = "0";
        if (can_use_data_cash.size() != 0) {
            maxDiscount = can_use_data_cash.get(0).amt;
            discountId = can_use_data_cash.get(0).serial_id;
            for (int i = 0; i < can_use_data_cash.size(); i++) {
                if (MathUtils.compare(maxDiscount, can_use_data_cash.get(i).amt) < 0) {
                    maxDiscount = can_use_data_cash.get(i).amt;
                    discountId = can_use_data_cash.get(i).serial_id;
                }
            }

            if (redEnvelop != null && MathUtils.compare(maxDiscount, redEnvelop) < 0) {
                maxDiscount = redEnvelop;
                discountId = "";
            }

        } else {
            if (redEnvelop != null) {
                maxDiscount = redEnvelop;
                discountId = "";
            }
        }

        discount_money = maxDiscount;

        //限制优惠卷起投金额，限制
        bv_preferential.getmSubTitle().setText(getString(R.string._yuan, maxDiscount));
        if (et_investmoney.getText().toString().isEmpty() || MathUtils.compare(et_investmoney.getText().toString(), maxDiscount) <= 0) {
            bv_payable.getmSubTitle().setText(getString(R.string._rmb, 0));
        } else {
            bv_payable.getmSubTitle().setText(getString(R.string._rmb, Double.valueOf(et_investmoney.getText().toString()) - Double.valueOf(maxDiscount)));
        }
    }


    /**
     * 计算收益，做ui更新
     */
    @SuppressWarnings("deprecation")
    private void income(String money) {
        //防止""时候下面代码抛出异常
        if (money == null || money.isEmpty() || MathUtils.equals("0", money)) {
            return;
        }
        //利率存在但是为零
        if (new BigDecimal(rate).compareTo(new BigDecimal(0)) == 0) {
            tv_incomesum.setText("0");
        } else {
            investAmnt = money;

            BigDecimal touZi = new BigDecimal(investAmnt);

            BigDecimal rate = null;
            if (CommTool.isDouble(this.rate)) {
                rate = new BigDecimal(this.rate);
            } else {
                rate = new BigDecimal(0);
            }

            BigDecimal term = null;
            if (CommTool.isDouble(this.term)) {
                term = new BigDecimal(this.term);
            } else {
                term = new BigDecimal(0);
            }

            try {
                BigDecimal monthRate = rate.divide(new BigDecimal(12), 10, BigDecimal.ROUND_HALF_EVEN);
                BigDecimal income = null;

                switch (pay_method) {
                    case "1":
                        //到期还本息付
                        income = touZi.multiply(rate).multiply(term).divide(new BigDecimal(360), 5, BigDecimal.ROUND_HALF_EVEN);
                        break;
                    case "2":
                        //按月还息到期还本
                        income = touZi.multiply(monthRate).multiply(term);
                        break;
                    case "3":
                        //等额本息
                        BigDecimal pow = (monthRate.add(new BigDecimal(1))).pow(term.intValue());
                        income = (touZi.multiply(monthRate).multiply(pow).divide(pow.subtract(new BigDecimal(1)), 10, BigDecimal.ROUND_HALF_EVEN)).multiply(term).subtract(touZi);
                        break;
                    case "4":
                        //等额本金
                        income = touZi.multiply(monthRate).multiply((term.add(new BigDecimal(1)))).divide(new BigDecimal(2), 10, BigDecimal.ROUND_HALF_EVEN);
                        break;
                    default:
                        income = touZi.multiply(rate).multiply(term).divide(new BigDecimal(360), 10, BigDecimal.ROUND_HALF_EVEN);
                        break;
                }
                tv_incomesum.setText(CommTool.moneyOneThousandsFormat(income.toString()));
            } catch (Exception e) {
                tv_incomesum.setText("");
            }

        }
    }

    /**
     * 接受dialog的点击事件
     *
     * @param o
     * @param position
     */
    @Override
    public void onItemClick(Object o, int position) {
        if (isFastDoubleClick()) {
            return;
        }
        // TODO Auto-generated method stub
        if ((HSDialog) o == dialog_rechange) {
            if (position != -1) {
                readyGo(RechangeNewActivity.class);
            }
        } else if ((HSDialog) o == riskDialog) {
            //开启riskdialog风险评估
            if (position != -1) {
                if (sharedPreferences.getShareProf(UserInfo.OLD) != null) {
                    if (sharedPreferences.getShareProf(UserInfo.OLD).isEmpty() || MathUtils.compare(sharedPreferences.getShareProf(UserInfo.OLD), "18") < 0 || MathUtils.compare(sharedPreferences.getShareProf(UserInfo.OLD), "68") >= 0) {
                        showToast(getString(R.string.age_not_risk));
                        return;
                    }
                }

                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                        TaskConstants.TASK_RISKESTIMATE, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap = new HeaderMap();
                headerMap.setMap(hearder);
                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.risk_estimate));
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, getString(R.string.root_h5_url_test) + getString(R.string.h5_user) + TaskConstants.TASK_RISKESTIMATE);
                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebRiskActivity.class, bundle);
            }
        } else if ((HSDialog) o == riskSureDialog) {
            if (position != -1) {
                riskSureDialog.dismiss();
                riskSureDialog.setOnDismissListener(new HSDialog.HSDialogOnDismissListener() {
                    @Override
                    public void onDismiss(Object o) {
                        dialog_buy = new HSDialog(null, getString(R.string.tips_buy), getString(R.string.cancel),
                                getString(R.string.buy), mContext, InvestActivity.this).setCancelable(false);//.setOnDismissListener(this);
                        dialog_buy.show();
                    }
                });
            }
        } else if ((HSDialog) o == paypwdDialog) {
            if (position != -1) {
//                zwgt_data = BaseRequestTool2.getFormatedDateString();
//                JSONObject map1 = new JSONObject();
//
//                try {
//                    map1.put("vcode", "");
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//                JSONObject jsonParams = CommTool.getJSONParams(map1, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
//                mPresenter.loadingData(TaskConstants.TASK_SETBANKPWD, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_user_test) + TaskConstants.TASK_SETBANKPWD, Constants.EVENT_DATA,
//                        jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_user_test) + TaskConstants.TASK_SETBANKPWD, sharedPreferences
//                                .getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
                readyGo(ManagementActivity.class);
            }
        } else if ((HSDialog) o == authDialog) {
            if (position != -1) {
                readyGo(ManagementActivity.class);
            }
        }
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
        // TODO Auto-generated method stub
        if (TextUtils.equals(task_name, TaskConstants.TASK_INVEST)) {
            //用户点击投资之后发现余额不足弹出充值框
            if (TextUtils.equals("300329", data.toString())) {
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                        TaskConstants.TASK_RISKESTIMATE, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap = new HeaderMap();
                headerMap.setMap(hearder);
                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.risk_estimate));
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, getString(R.string.root_h5_url_test) + getString(R.string.h5_user) + TaskConstants.TASK_RISKESTIMATE);
                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebRiskActivity.class, bundle);
                return;
            }

            // TODO: 2017/5/31 有一个地方没有完全理解
            zwgt_data = BaseRequestTool2.getFormatedDateString();
            HashMap<String, String> hearder1 = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                    "investsucess", sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
            HeaderMap headerMap1 = new HeaderMap();
            headerMap1.setMap(hearder1);
            Bundle bundle = new Bundle();
           /* bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, LoadType.DATA.getIntValue());
            bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.pay_order));
            bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, (String) data);
            bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap1);
            bundle.putString("INVESTAMOUNT", et_investmoney.getText().toString());
            readyGoThenKill(WebPayActivity.class, bundle);*/

            Log.e("ddd", String.valueOf(data));
            bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, (String) data);
            bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap1);
            bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
            readyGo(WebOpenAccountActivity.class, bundle);

        } else if (TextUtils.equals(task_name, TaskConstants.TASK_PROTOCOL)) {
            InvestProtocolBean investProtocolBean = (InvestProtocolBean) data;
            Bundle bundle = new Bundle();

            if ("INVESTMENT_PROTOCOL".equals(protocol)) {
                bundle.putString("protocol_name", investProtocolBean.protocol_name);
                bundle.putString("protocol_url", investProtocolBean.protocol_url);
                readyGo(InvestProtocolActivity.class, bundle);
            } else if ("RISK_DISCLOSURE".equals(protocol)) {
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, investProtocolBean.protocol_name1);
                bundle.putString(WebProtocolActivity.PROTOCOL_CODE, EnumProtocol.findCode(EnumProtocol.HELP));
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, investProtocolBean.protocol_url1);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, LoadType.HTTP.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebActivity.class, bundle);
            }
        } else if (TextUtils.equals(task_name, TaskConstants.TASK_SETBANKPWD)) {
            if (data == null) {
                return;
            }

            UpdatePayPwdBeen mUpdatePayPwdBeen = (UpdatePayPwdBeen) data;

            //现在做另外一种操作
            String postData = null;
            try {
                postData = "accountId=" + URLEncoder.encode(mUpdatePayPwdBeen.data.accountId.toString(), "utf-8") + "&acqRes=" + URLEncoder.encode(mUpdatePayPwdBeen.data.acqRes.toString(), "utf-8") +
                        "&bankCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.bankCode.toString(), "utf-8") + "&channel=" + URLEncoder.encode(mUpdatePayPwdBeen.data.channel.toString(), "utf-8") +
                        "&idNo=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idNo.toString(), "utf-8") + "&idType=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idType.toString(), "utf-8") + "&instCode=" +
                        URLEncoder.encode(mUpdatePayPwdBeen.data.instCode.toString(), "utf-8") + "&lastSrvAuthCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.lastSrvAuthCode == null ? "" : mUpdatePayPwdBeen.data.lastSrvAuthCode.toString(), "utf-8") +
                        "&mobile=" + URLEncoder.encode(mUpdatePayPwdBeen.data.mobile.toString(), "utf-8") + "&name=" + URLEncoder.encode(mUpdatePayPwdBeen.data.name.toString(), "utf-8") + "&notifyUrl=" +
                        URLEncoder.encode(mUpdatePayPwdBeen.data.notifyUrl.toString(), "utf-8") + "&retUrl=" + URLEncoder.encode(mUpdatePayPwdBeen.data.retUrl.toString(), "utf-8") + "&seqNo=" +
                        URLEncoder.encode(mUpdatePayPwdBeen.data.seqNo.toString(), "utf-8") + "&sign=" + URLEncoder.encode(mUpdatePayPwdBeen.data.sign.toString(), "utf-8") + "&smsCode=" +
                        URLEncoder.encode(mUpdatePayPwdBeen.data.smsCode == null ? "" : mUpdatePayPwdBeen.data.smsCode.toString(), "utf-8") + "&txCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txCode.toString(), "utf-8") +
                        "&txDate=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txDate.toString(), "utf-8") + "&txTime=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txTime.toString(), "utf-8") + "&version=" +
                        URLEncoder.encode(mUpdatePayPwdBeen.data.version.toString(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Logs.e("e.toString: " + e.toString());
            }

            Bundle bundle = new Bundle();
            bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.set_paywd));
            bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, mUpdatePayPwdBeen.url);
            bundle.putString(BaseWebActivity.BUNDLE_KEY_PARAMS, postData);
            bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.POSTDATA.getIntValue());
            bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
            readyGo(WebSetPasswordActivity.class, bundle);
        } else if (TextUtils.equals(task_name, TaskConstants.TASK_DISCOUNT)) {
            if (data == null) {
                return;
            }

            //获取红包优惠券信息
            DiscountBeen discountBean = (DiscountBeen) data;
            if (discountBean.redEnvelop != null && !discountBean.redEnvelop.equals("0.00")) {
                redEnvelop = discountBean.redEnvelop;
            }

            List<DiscountBeen.DiscountBean> discounts = discountBean.discount;
            data_cash.addAll(discounts);

            discountChoice(et_investmoney.getText().toString());


        } else if (TextUtils.equals(task_name, TaskConstants.TASK_BEFOREINVEST)) {
            BeforeInvestBean beforeInvestBean = (BeforeInvestBean) data;
            Log.e("beforeInvestBean.status", beforeInvestBean.status + "");
            switch (beforeInvestBean.status) {
                case 0://未测评
                    riskDialog = new HSDialog(getString(R.string.risk_login), beforeInvestBean.msg, getString(R.string.zbtz),
                            getString(R.string.evaluate_immediately), this, this).setCancelable(false);//.setOnDismissListener(this);
                    riskDialog.show();
                    break;
                case 1://测评通过可投资
                    String amount = et_investmoney.getText().toString();
                    String goodsid = goodsId;
                    String discountid = "";
                    String discountamt = "";
                    discountid = discountId;
                    discountamt = discount_money;
                    //获取时间
                    String zwgt_data = BaseRequestTool2.getFormatedDateString();
                    JSONObject map = new JSONObject();
                    try {
                        map.put("amount", amount);
                        map.put("discountid", discountid);
                        map.put("discountamt", discountamt);
                        map.put("goodsid", goodsid);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    //token前24为作为key，zwgt_data后8为作为iv
                    JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);

                    //投资网络请求
                    mPresenter.loadingData(TaskConstants.TASK_INVEST, getString(R.string.root_url_test) + getString(R.string.api_trade_test) + TaskConstants.TASK_INVEST, Constants
                            .EVENT_REFRESH_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_trade_test)
                            + TaskConstants.TASK_INVEST, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
                    break;
                case 2://测评不通过
                    riskDialog = new HSDialog(getString(R.string.tips), beforeInvestBean.msg, getString(R.string.next_say),
                            getString(R.string.again_risk), this, this).setCancelable(false);//.setOnDismissListener(this);
                    riskDialog.show();
                    break;

                case 3://未进行缴费授权
                    authDialog = new HSDialog(getString(R.string.tips), beforeInvestBean.msg, getString(R.string.cancel),
                            getString(R.string.sure), this, this).setCancelable(false);//.setOnDismissListener(this);
                    authDialog.show();
                    break;
            }
        }
        hideLoading();
    }

    @Override
    public <T> void initializeError(String task_name, T data) {
        // TODO Auto-generated method stub
        hideLoading();
    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == event.KEYCODE_BACK) {
            if (dialog_rechange != null && dialog_rechange.isShowing()) {
                dialog_rechange.dismiss();
                return true;
            } else if (dialog_buy != null && dialog_buy.isShowing()) {
                dialog_buy.dismiss();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PREFERENTIAL) {
            if (data == null) {
                return;
            }

            discount = (DiscountInfoBean) data.getSerializableExtra("discountinfobean");
            discountId = discount.id;
            discount_money = discount.money;
            discount_can_user_min_money = discount.min_money;

            //限制优惠卷起投金额，限制
            bv_preferential.getmSubTitle().setText(getString(R.string._yuan, discount_money));
            if (et_investmoney.getText().toString().isEmpty() || discount_money.isEmpty() || MathUtils.compare(et_investmoney.getText().toString(), discount_money) <= 0) {
                bv_payable.getmSubTitle().setText(getString(R.string._rmb, 0));
            } else {
                bv_payable.getmSubTitle().setText(getString(R.string._rmb, Double.valueOf(et_investmoney.getText().toString()) - Double.valueOf(discount_money)));
            }
        }
    }

    private void showProgressToDismiss() {
        showProgress("");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                closeProgress();
            }
        }, 2000);
    }
}
